<?php
//数据库初始化文件
function read_critical() {
    if (strstr($_SERVER['SCRIPT_FILENAME'],'/ajax/auto') || 
        strstr($_SERVER['SCRIPT_FILENAME'],'/modules/space.php') ||
        strstr($_SERVER['SCRIPT_FILENAME'],'/modules/vote.php') ||
        strstr($_SERVER['SCRIPT_FILENAME'],'/modules/pk.php') ||
        strstr($_SERVER['SCRIPT_FILENAME'],'/ajax/pk.php') ||
        strstr($_SERVER['SCRIPT_FILENAME'],'/modules/friend.php') ||
        strstr($_SERVER['SCRIPT_FILENAME'],'/modules/index.php')) {
        return false;
    } else {
        return true;
    }
}

class mysqli_facekoo extends mysqli {
    public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
        $result = parent::query($query, $resultmode);
        if (!$result) {
            error_log("MYSQL ERROR: ".$this->error." (STMT: $query) (URL: ".$_SERVER['REQUEST_URI'].")");
        }
        return $result;
    }
}


global $mysqli_read;
global $mysqli_write;
global $is_production;

$is_production = getenv("FACEKOO_PRODUCTION");

if ($is_production) {
    $dbhost_read = '192.168.2.104';
    $dbhost_write = '192.168.2.103';
    $dbuser = 'facekoo';
    $dbpass = trim(file_get_contents('/usr/local/facekoo/conf/mysql_password'));
    $dbname = 'facekoo3';
    //    $faceserver_host = "192.168.2.101";
} else {
    $dbhost_read = '127.0.0.1';
    $dbhost_write = '127.0.0.1';
    $dbuser = 'root';
    $dbpass = '4136705';			   
    $dbname = 'mtime';
    //    $faceserver_host = "192.168.1.5";
}
$mysqli_write = new mysqli_facekoo($dbhost_write, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) { 
    printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()); 
    exit; 
}
if (!$mysqli_write->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli_write->error);
    exit;
}

if (read_critical() || !$is_production) {
    $mysqli_read = $mysqli_write;
} else {
    $mysqli_read = new mysqli_facekoo($dbhost_read, $dbuser, $dbpass, $dbname); 
    if (mysqli_connect_errno()) {
        printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()); 
        exit;
    }
    if (!$mysqli_read->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli_read->error);
        exit;
    }
}

?>
